package com.pmt.feedplayer.core

import android.content.Context
import com.google.mlkit.common.model.DownloadConditions
import com.google.mlkit.nl.translate.TranslateLanguage
import com.google.mlkit.nl.translate.Translation
import com.google.mlkit.nl.translate.TranslatorOptions
import kotlinx.coroutines.Dispatchers
import kotlinx.coroutines.withContext
import kotlinx.coroutines.tasks.await
import java.util.concurrent.ConcurrentHashMap

/**
 * Android平台翻译器实现
 * 使用Google ML Kit翻译API
 */
class AndroidTranslator(private val context: Context) : Translator {
    // 缓存翻译器实例，避免重复创建
    private val translators = ConcurrentHashMap<String, com.google.mlkit.nl.translate.Translator>()
    private var isRunning = true
    
    override suspend fun translate(text: String, sourceLang: String, targetLang: String): String {
        if (text.isEmpty()) return ""
        
        try {
            val translator = getOrCreateTranslator(sourceLang, targetLang)
            
            // 下载模型（如果需要）
            val conditions = DownloadConditions.Builder()
                .requireWifi() // 可选：仅在WiFi下下载
                .build()
            translator.downloadModelIfNeeded(conditions)
                .await()
            
            // 执行翻译
            return withContext(Dispatchers.IO) {
                translator.translate(text).await()
            }
        } catch (e: Exception) {
            println("Translation error: ${e.message}")
            // 出错时返回原文
            return text
        }
    }
    
    override suspend fun batchTranslate(texts: List<String>, sourceLang: String, targetLang: String): List<String> {
        return texts.map { translate(it, sourceLang, targetLang) }
    }
    
    override fun stop() {
        isRunning = false
        // 释放所有翻译器资源
        translators.values.forEach { it.close() }
        translators.clear()
    }
    
    private fun getOrCreateTranslator(sourceLang: String, targetLang: String): com.google.mlkit.nl.translate.Translator {
        val key = "$sourceLang-$targetLang"
        
        return translators.computeIfAbsent(key) { 
            // 将语言代码转换为ML Kit支持的语言代码
            val sourceLanguageCode = convertToMlKitLanguageCode(sourceLang)
            val targetLanguageCode = convertToMlKitLanguageCode(targetLang)
            
            val options = TranslatorOptions.Builder()
                .setSourceLanguage(sourceLanguageCode)
                .setTargetLanguage(targetLanguageCode)
                .build()
            
            Translation.getClient(options)
        }
    }
    
    private fun convertToMlKitLanguageCode(languageCode: String): String {
        // 映射语言代码到ML Kit支持的格式
        return when (languageCode.lowercase()) {
            "ja", "japanese" -> TranslateLanguage.JAPANESE
            "zh", "chinese", "zh-cn" -> TranslateLanguage.CHINESE
            "en", "english" -> TranslateLanguage.ENGLISH
            "ko", "korean" -> TranslateLanguage.KOREAN
            "fr", "french" -> TranslateLanguage.FRENCH
            "de", "german" -> TranslateLanguage.GERMAN
            "es", "spanish" -> TranslateLanguage.SPANISH
            else -> languageCode // 如果没有映射，使用原始代码
        }
    }
    
    /**
     * 替代实现：使用HTTP API进行翻译（如果ML Kit不可用）
     */
    private suspend fun translateWithHttpApi(text: String, sourceLang: String, targetLang: String): String {
        // 这里可以实现HTTP API调用逻辑
        // 例如使用Google Translate API, DeepL等
        // 注意：实际使用需要申请API密钥并处理认证
        return text // 简化实现，返回原文
    }
    
    /**
     * 释放资源
     */
    fun release() {
        stop()
    }
}